document.addEventListener('click', function (event) {
    let clickedElementXPath = 'html/' + getElementXPath(event.target);
    console.log('被点击元素的XPath：', clickedElementXPath);
    record({
        "type": 'click',
        "xpath": clickedElementXPath
    })

});
// 监听键盘输入事件
// document.addEventListener('keyup', function (event) {
//     const key = event.key;
//     record('keyup', clickedElementXPath)
//
// });
document.addEventListener("compositionend", function (event) {
    let inputText = event.data;
    console.log("输入完成的字符: " + inputText);
    let clickedElementXPath = 'html/' + getElementXPath(event.target);
    record(
        {
            "type": 'compositionend',
            "xpath": clickedElementXPath,
            "input":inputText
        }
    )
});


function record(data) {
    fetch('http://127.0.0.1:8000/', {
        method: 'POST',
        body: JSON.stringify(data)
    })
}

function getElementXPath(element) {
    if (element === document.body)
        return 'body';

    let ix = 0;
    let siblings = element.parentNode.childNodes;
    for (let i = 0; i < siblings.length; i++) {
        let sibling = siblings[i];
        if (sibling === element)
            return getElementXPath(element.parentNode) + '/' + element.tagName.toLowerCase() + '[' + (ix + 1) + ']';
        if (sibling.nodeType === 1 && sibling.tagName === element.tagName)
            ix++;
    }
}